package com.kongjs.application.util;

import cn.hutool.core.lang.tree.Tree;
import com.kongjs.application.model.vo.TreeVO;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.*;

public class TreeUtil {
    /*
    * 统一树形结构
    * */
    public static <ID, T extends TreeVO<T, ID>> List<T> buildTree(List<T> list) {
        List<T> root = new ArrayList<>();
        Map<ID, T> map = new HashMap<>(list.size());
        for (T t : list) {
            t.setChildren(new ArrayList<>());
            map.put(t.getId(), t);
        }
        for (T t : list) {
            if (ObjectUtils.isEmpty(t.getParentId()) || t.getParentId().equals(0L)) {
                root.add(t);
            } else {
                T t1 = map.get(t.getParentId());
                t1.getChildren().add(t);
            }
        }
        if (CollectionUtils.isEmpty(root)) {
            return list;
        }
        return root;
    }
}

